﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Zop;

namespace ImgUpload.Controllers
{
    //[Produces("application/json")]
    //[Consumes("application/json", "multipart/form-data")]//此处为新增
    [Route("[controller]")]
    [ApiController]
    public class UploadController : ControllerBase
    {
        private readonly AliyunService _aliYunService;
        private readonly ILogger<UploadController> _logger;
        public UploadController(AliyunService aliYunService, ILogger<UploadController> logger)
        {
            _aliYunService = aliYunService;
            _logger = logger;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public Task<JsonResult> Index(IFormCollection files)
        {
            ImageType? imagetype = null;
            string userName = "";
            try
            {
                string imgType = Request.Query["type"];
                userName = Request.Query["code"];
                if (string.IsNullOrEmpty(imgType))
                    imgType = files["type"].ToString().ToLower();
                else
                    imgType = imgType.ToLower();
                imagetype = (ImageType)Enum.Parse(typeof(ImageType), imgType);

                if (!base.ModelState.IsValid || imagetype == null || userName == "")
                    return Task.FromResult(new JsonResult( Result.ReFailure("参数错误")));
                
                Stream st = null;
                foreach (IFormFile formFile in files.Files)
                {
                    if (formFile.Name == "ImgByte")
                    {
                        st = formFile.OpenReadStream();
                    }
                }

                string file = _aliYunService.Upload(imagetype.ToString(), userName, st);
                //int index = file.IndexOf(imagetype.ToString());
                //string imgPath = file.Substring(index, file.Length - index).Replace("\\", "/");
                
                if (file.Equals(""))
                    return Task.FromResult(new JsonResult(Result.ReFailure("上传失败")));
                else
                    return Task.FromResult(new JsonResult(new Result(file, "success")));
            }
            catch (Exception ex)
            {
                _logger.LogError($"imagetype:{imagetype},userName:{userName},ex:{ex.ToString()}");
                return Task.FromResult(new JsonResult(Result.ReFailure("参数错误")));
            }
        }
    }
}